package service

import (
	"fmt"
	"mime/multipart"
	conf "my-systems/pet-system/configs"
	"my-systems/pet-system/internal/info"
	"my-systems/pet-system/internal/models"
	"my-systems/pet-system/internal/sql/user_sql"
	"my-systems/pet-system/pkg/e"
	"my-systems/pet-system/pkg/tools"
	"net/http"
	"strconv"
)

type UserService struct {
	Username string `json:"username" form:"username"`
	Password string `json:"password" form:"password"`
	Avatar   string `json:"avatar" form:"avatar"`
	Phone    string `json:"phone" form:"phone"`
	Email    string `json:"email" form:"email"`
	Address  string `json:"address" form:"address"`
	Sex      string `json:"sex" form:"sex"`
	Birthday string `json:"birthday" form:"birthday"`
	Balance  string `json:"balance" form:"balance" ` // 初始金额
	Key      string `json:"key" form:"key" `         // 用户密钥
}

func (us *UserService) RegisterUser() info.Response {
	var user models.User
	code := http.StatusOK

	if len(us.Key) != 16 {
		return info.Response{
			Status: http.StatusBadRequest,
			Msg:    "密钥长度错误",
		}
	}
	// 加密操作
	tools.Encrypt.SetKey(us.Key)
	// 检查用户是否存在
	_, exist, err := user_sql.ExistOrNotByUsername(us.Username)
	if err != nil {
		code := http.StatusInternalServerError
		return info.Response{
			Status: code,
			Msg:    e.GetMsgInfo(code),
		}
	}
	if exist {
		code := e.TheUserExists
		return info.Response{
			Status: code,
			Msg:    e.GetMsgInfo(code),
		}
	}
	// 初始金额加密
	var balanceTmp string
	if us.Balance == "0" || us.Balance == "" {
		balanceTmp, err = tools.Encrypt.MyEncrypt("0")
	} else {
		balanceTmp, err = tools.Encrypt.MyEncrypt(us.Balance)
	}
	if err != nil {
		code := http.StatusInternalServerError
		return info.Response{
			Status: code,
			Msg:    "加密失败" + err.Error(),
		}
	}
	user = models.User{
		//Model:    gorm.Model{},
		Username: us.Username,
		//Password: "",
		Avatar:   "default_User_Image.jpg",
		Phone:    us.Phone,
		Email:    us.Email,
		Address:  us.Address,
		Sex:      us.Sex,
		Birthday: us.Birthday,
		Balance:  balanceTmp,
	}

	// 密码加密
	err = user.SetPassword(us.Password)
	if err != nil {
		code := http.StatusInternalServerError
		return info.Response{
			Status: code,
			Msg:    "加密失败" + err.Error(),
		}
	}
	// 创建用户
	err = user_sql.RegisterUserMethod(&user)
	if err != nil {
		code := http.StatusInternalServerError
		return info.Response{
			Status: code,
			Msg:    "创建用户失败" + err.Error(),
		}
	}
	//fmt.Println("注册成功")
	return info.Response{
		Status: code,
		Msg:    "注册--" + e.GetMsgInfo(code),
	}

}

func (us *UserService) LoginUser() info.Response {
	code := http.StatusOK
	// 检查用户是否存在
	user, exist, err := user_sql.ExistOrNotByUsername(us.Username)
	if err != nil {
		code := http.StatusBadRequest
		return info.Response{
			Status: code,
			Msg:    e.GetMsgInfo(code),
			Error:  err.Error(),
		}
	}
	fmt.Println(exist, us.Username, user)
	if !exist {
		code := e.TheUserNotExists
		return info.Response{
			Status: code,
			Msg:    e.GetMsgInfo(code),
		}
	}
	// 检查密码是否正确
	if !user.CheckPassword(us.Password) {
		code := e.ThePasswordIsIncorrect
		return info.Response{
			Status: code,
			Msg:    e.GetMsgInfo(code),
		}
	}
	// 密码正确，生成token-->普通用户权限
	token, err := tools.CreateToken(int(user.ID), user.Username, tools.NormalUser)
	if err != nil {
		code := e.CreateTokenERROR
		return info.Response{
			Status: code,
			Msg:    e.GetMsgInfo(code),
			Error:  err.Error(),
		}
	}
	return info.Response{
		Status: code,
		Msg:    e.GetMsgInfo(code),
		Data: info.TokenData{
			User:  info.BuildUser(user),
			Token: token,
		},
	}
}

func (us *UserService) UpdateUser(uid int) info.Response {
	code := http.StatusOK
	user := &models.User{
		Username: us.Username,
		Phone:    us.Phone,
		Address:  us.Address,
		Sex:      us.Sex,
		Birthday: us.Birthday,
	}
	err := user_sql.UpdateUserInfo(nil, uid, user)
	if err != nil {
		code = http.StatusBadRequest
		return info.Response{
			Status: code,
			Msg:    e.GetMsgInfo(code),
			Error:  err.Error(),
		}
	}
	return info.Response{
		Status: code,
		Msg:    "更新成功" + e.GetMsgInfo(code),
	}
}

func (us *UserService) UpAvatar(uid int, file multipart.File) info.Response {
	code := http.StatusOK
	user, _ := user_sql.GetUserByID(uid)
	// 保存图片文件到本地
	path, err := UploadAvatarToLocalStatic(uid, user.Username, file, "user")
	if err != nil {
		return info.Response{
			Status: http.StatusBadRequest,
			Msg:    "上传头像失败",
			Error:  err.Error(),
		}
	}
	user.Avatar = path
	err = user_sql.UpAvatar(uid, user)
	if err != nil {
		return info.Response{
			Status: http.StatusBadRequest,
			Msg:    "更新头像失败",
			Error:  err.Error(),
		}
	}
	user.Avatar = conf.URLHost + conf.ServerPort + conf.AvatarPath + path
	return info.Response{
		Status: code,
		Msg:    "更新成功" + e.GetMsgInfo(code),
		Data:   "新头像地址：" + user.Avatar,
	}
}

func (us *UserService) RechargeSQL(uid int) interface{} {
	code := http.StatusOK
	// 获取支付密码key
	tools.Encrypt.SetKey(us.Key)
	fmt.Println("key:", us.Key)
	// 验证充值金额是否有效
	rechargeAmount, err := strconv.ParseFloat(us.Balance, 64)
	if err != nil || rechargeAmount <= 0 {
		code = e.TheTopUpAmountIsInvalid
		return info.Response{
			Status: code,
			Msg:    e.GetMsgInfo(code),
			Error:  err.Error(),
		}
	}

	// 开启事务
	tx := user_sql.DB.Begin()
	if tx.Error != nil {
		code = http.StatusInternalServerError
		return info.Response{
			Status: code,
			Msg:    "开启事务失败",
			Error:  tx.Error.Error(),
		}
	}

	// 获取当前用户余额
	user, err := user_sql.GetUserByID(uid)
	if err != nil {
		code := http.StatusBadRequest
		return info.Response{
			Status: code,
			Error:  err.Error(),
		}
	}
	// 解密余额
	decryptAmount, err := tools.Encrypt.MyDecrypt(user.Balance)
	if err != nil {
		tx.Rollback() // 解密失败回滚
		code = e.ThePaymentKeyWasEnteredIncorrectly
		return info.Response{
			Status: code,
			Msg:    e.GetMsgInfo(code),
			Error:  err.Error(),
		}
	}
	// 转化解密后的余额为数值类型
	currencyBalance, err := strconv.ParseFloat(decryptAmount, 64)
	if err != nil {
		tx.Rollback()
		code = http.StatusBadRequest
		return info.Response{
			Status: code,
			Msg:    "解析余额失败",
			Error:  err.Error(),
		}
	}
	// 计算新的余额
	newBalance := currencyBalance + rechargeAmount
	// 加密新余额
	newBalanceStr := strconv.FormatFloat(newBalance, 'f', 2, 64)
	encryptBalance, err := tools.Encrypt.MyEncrypt(newBalanceStr)
	if err != nil {
		tx.Rollback()
		code = http.StatusBadRequest
		return info.Response{
			Status: code,
			Msg:    "加密余额失败",
			Error:  err.Error(),
		}
	}
	upBalance := &models.User{Balance: encryptBalance}
	err = user_sql.UpdateUserInfo(tx, uid, upBalance)
	if err != nil {
		tx.Rollback()
		code = http.StatusBadRequest
		return info.Response{
			Status: code,
			Msg:    "更新余额失败",
			Error:  err.Error(),
		}
	}
	// 提交事务
	if err := tx.Commit().Error; err != nil {
		code = http.StatusBadRequest
		return info.Response{
			Status: code,
			Msg:    "提交事务失败",
			Error:  err.Error(),
		}
	}
	return info.Response{
		Status: code,
		Msg:    "更新余额成功" + e.GetMsgInfo(code),
	}

}

func (us *UserService) CatMoneySQL(uid int) interface{} {
	code := http.StatusOK
	// 获取支付密码key
	tools.Encrypt.SetKey(us.Key)
	fmt.Println("key:", us.Key)
	// 获取当前用户余额
	user, err := user_sql.GetUserByID(uid)
	if err != nil {
		code := http.StatusBadRequest
		return info.Response{
			Status: code,
			Error:  err.Error(),
		}
	}
	// 解密余额
	decryptAmount, err := tools.Encrypt.MyDecrypt(user.Balance)
	if err != nil {
		code = e.ThePaymentKeyWasEnteredIncorrectly
		return info.Response{
			Status: code,
			Msg:    e.GetMsgInfo(code),
			Error:  err.Error(),
		}
	}

	return info.Response{
		Status: code,
		Msg:    "查询余额成功",
		Data:   user.Username + "的余额为" + decryptAmount,
	}
}
